// pages/category/category.js
import { CategoryModel } from '../../models/CategoryModel.js'
import { CartModel } from '../../models/CartModel.js'

let category = new CategoryModel()
let Cart = new CartModel()


Page({

  /**
   * 页面的初始数据
   */
  data: {
    menuCategories: [],
    menuSelect:0,
    menuNmae:'',
    products:[],
    product:{},
    show:false
  },

   /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._init()
    console.log('load',options)
  },
  onShow:function(){
    this.setData({
      show:false
    })
  },
  // 图书购物车图标
  addCart:function(e){
    let show = e.detail.show
    let product = e.detail.product
    console.log('e',e.detail)
    this.setData({
      show:show,
      product:product
    })
  },
  joinCart:function(e){
    let count = e.detail.count
    this.setData({
      show:true
    })
    Cart.add(this.data.product,count,res=>{
      this.setData({
        show:false
      })
      wx.showToast({
        icon:"success",
        context:"添加成功",
        title:'添加成功'
      })
    })
  },
    // 弹出框，立即购买
    buy:function(e){
      let count = e.detail.count
      wx.navigateTo({
        url: '../order/order?count='+count+'&from=product'+'&productId='+this.data.product._id,
      })
    },
  onChange(event) {
    let menuSelect = event.detail.name
    console.log('menuSelect',event)
    this.setData({
      menuSelect:menuSelect
    })
    this._getCateGory(menuSelect)
    console.log('change',this.data.products)
  },
  // 初始化数据
  _init:function(){
    category.getCateGory(res=>{
      console.log('category',res.result.data.data)
      let categories = res.result.data.data
      this.setData({
        menuCategories:categories,
        menuSelect:categories[0].category_type
      })
    })
  },
  // 菜单切换
  menu:function(e){
    let index = category.getDataSet(e, "index")
    console.log('index',index)
    let menuCategories = this.data.menuCategories
    let menuSelect = menuCategories[index].category_type
    let menuNmae = menuCategories[index].category_name
    console.log('category_type',menuSelect)
    this._getCateGory(menuSelect)

    this.setData({
      menuSelect,
      menuNmae
    })
  },
  // 跳转商品详情
  showDetail:function(e){
    console.log('navigateto')
    wx.navigateTo({
      url: '/pages/product/product?product_id=' + e.detail.productId,
    })
  },
  _getCateGory:function(type){
    category.getCateGoryProduct(type, data => {
      this.setData({
        products: data.result.data.data
      })
    })
  }
})
